<?php
/**
 * @修改：Chris
 * @时间:    2018-09-04 10:35:50
 * @功能: 公司管理
 */

header('Access-Control-Allow-Origin: *');
require( "config.php");

$op = $_POST['op'];
$p = $_POST;

// insert
if($op == 'add'){
	$data['companyName'] = $p['companyName'];//商户名称
	$data['companyAddr'] = $p['companyAddr'];//商户地址
	$data['companyPhone'] = $p['companyPhone'];//商户电话

	$admin['roleid'] = 0;//持所有权限身份
	if (!isset($p['roleid'])) {
		/*检测公司名称是否重复*/ 
		$where = 'companyName = "'.$p['companyName'].'"';
		$check_admin_username = $db->select('ci_company','*',$where);
		if ($check_admin_username) {
			die('添加失败');
		}
		$companyId = $db->insert('ci_company',$data);
	}else{
		$where = 'companyName = "'.$p['companyName'].'"';
		$company = $db->select('ci_company','*',$where);
		$companyId = $company[0]['id'];
		$admin['roleid'] = $p['roleid'];
		$admin['lever'] = $p['lever'];
		$admin['rightids'] = $p['rightids'];
		$admin['righttype1'] = $p['righttype1'];
		$admin['righttype2'] = $p['righttype2'];
		$admin['righttype4'] = $p['righttype4'];
		$admin['righttype8'] = $p['righttype8'];
	}
	$admin['username'] = $p['username'];//管理员账号
	$admin['userpwd'] = $p['userpwd'];//管理员密码
	$admin['status'] = 1;//状态
	$admin['name'] = $p['name'];//管理员名称
	$admin['mobile'] = $p['mobile'];//管理员手机号
	$admin['companyId'] = $companyId;//公司商户ID
	$adminId = $db->insert('ci_admin',$admin);

	if($companyId && $adminId){
		$re['status'] = '200';
		$re['msg'] = $id;
		$re['companyId'] = $companyId;
		if ($admin['roleid']==0) {
			die(json_encode($companyId));
		}else{
			die(json_encode($companyId));
		}
	}else{
		$re['status'] = '110';
		$re['msg'] = '添加失败';
		die('添加失败');
	}
	 // die(json_encode($re));
 }

//update 修改公司信息
if ($op == 'edit') {
	/*检测公司名称是否重复*/ 
	if (isset($p['companyName'])) {
		$where = 'companyName = "'.$p['companyName'].'" and id != '.$p['companyId'];
		$check_admin_username = $db->select('ci_company','*',$where);
		if ($check_admin_username) {
			die('添加失败');
		}
		$company['companyName'] = $p['companyName'];
		$company['companyAddr'] = $p['companyAddr'];
		$company['companyPhone'] = $p['companyPhone'];
		$where1 = 'id = '.$p['companyId'];
	 	$id = $db->update('ci_company',$company,$where1);
	}else{
		$id = 1;
	}

 	if (isset($p['username'])) {
 		$where2 = 'username = "'.$p['old_username'].'"';
	 	$admin['username'] = $p['username'];
	 	if ( $p['userpwd']!='') {
	 		$admin['userpwd'] = $p['userpwd'];
	 	}
	 	if (isset($p['name'])) {
	 		$admin['name'] = $p['name'];
	 	}
	 	if (isset($p['mobile'])) {
	 		$admin['mobile'] = $p['mobile'];
	 	}
	 	$id2 = $db->update('ci_admin',$admin,$where2);
 	}else{
 		$id2 = 1;
 	}

 	if($id && $id2){
 		die('添加成功');
 	}else{
 		die('添加失败');
 	}

}


 die('no op!');